package com.bigmi.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bigmi.common.cont.WemediaConstants;
import com.bigmi.file.service.FileStorageService;
import com.bigmi.model.common.dtos.PageResponseResult;
import com.bigmi.model.common.dtos.ResponseResult;
import com.bigmi.model.common.enums.AppHttpCodeEnum;
import com.bigmi.model.wemedia.dtos.WmMaterialDto;
import com.bigmi.model.wemedia.pojos.WmMaterial;
import com.bigmi.model.wemedia.pojos.WmNewsMaterial;
import com.bigmi.utils.thread.WmThreadLocalUtil;
import com.bigmi.wemedia.mapper.WmMediaMapper;
import com.bigmi.wemedia.mapper.WmNewsMaterialMapper;
import com.bigmi.wemedia.service.WmMaterialService;
import com.bigmi.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.UUID;

@Service
@Slf4j
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMediaMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmMediaMapper wmMediaMapper;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    /**
     * 素材图片上传
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //检查参数
        if (multipartFile==null || multipartFile.getSize()==0 ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //上传图片到minio
        //给图片命名uuid随机命名
        String filename = UUID.randomUUID().toString().replace("-", " ");
        //获取原文件名
        String originalFilename = multipartFile.getOriginalFilename();
        //将原文件名后缀进行截取
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String file =null;
        try {
            file = fileStorageService.uploadImgFile("", filename + substring, multipartFile.getInputStream());
            log.info("图片上传到minio"+file);
        } catch (IOException e) {
            log.error("图片上传失败");
            e.printStackTrace();
        }
        System.out.println(file);
        //保存到数据库
        WmMaterial wmMaterial =new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(file);
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short) 0);
        //Date time = TimeZone.getTimeZone("Etc/GMT-8");
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        //返回结果
        return ResponseResult.okResult(wmMaterial);
    }
    //素材列表查询
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //判断
        dto.checkParam();
        //分页查询
        IPage page =new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> queryWrapper =new LambdaQueryWrapper<>();
        //是否收藏
        if (dto.getIsCollection() !=null && dto.getIsCollection()==1){
            queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //按照用户查询
        queryWrapper.eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId());
        //按照时间排序
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        page = page(page, queryWrapper);
        //返回
        ResponseResult responseResult =new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        List records = page.getRecords();
        log.info(""+records);
        return responseResult;
    }

    /**删除图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "数据不存在");
        }
        //查询关系表如果图片被引用则不删除
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getMaterialId, id);
        log.info("" + queryWrapper);
        System.out.println("----------------------" + queryWrapper);
        List<WmNewsMaterial> wmNewsMaterialList = wmNewsMaterialMapper.selectList(queryWrapper);
        log.info("" + wmNewsMaterialList);
        if (wmNewsMaterialList.size() != 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "图片被文章引用无法删除");
        } else {
            wmMediaMapper.deleteById(id);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }


    }

    /**
     * 收藏图片
     * @param
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"图片不存在");
        }
        WmMaterial wmMaterial =new WmMaterial();
        wmMaterial.setId(id);
        //1收藏
        wmMaterial.setIsCollection(WemediaConstants.COLLECT_MATERIAL);
        int i = wmMediaMapper.updateById(wmMaterial);
        log.info(""+i);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult cancel_collect(Integer id) {
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"图片不存在");
        }
        WmMaterial wmMaterial =new WmMaterial();
        wmMaterial.setId(id);
        //0取消收藏
        wmMaterial.setIsCollection(WemediaConstants.CANCEL_COLLECT_MATERIAL);
        int i = wmMediaMapper.updateById(wmMaterial);
        log.info(""+i);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
